package com.example.healthy_station_flutter.receiver.time

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.example.healthy_station_flutter.MainActivity
import com.example.healthy_station_flutter.utils.TimeUtils
import io.flutter.embedding.android.FlutterActivity
import io.flutter.plugin.common.EventChannel

/**
 * 使用：lifecycle.addObserver(TimeReceiver(this))
 */
class TimeReceiver(val context: Context) : BroadcastReceiver(), LifecycleEventObserver {

    override fun onReceive(context: Context, intent: Intent) {
        if (Intent.ACTION_TIME_TICK == intent.action) {
            //更新时间
            TimeCallback.timeInterface?.updateTime(TimeUtils.instance.getTime(pattern = "yyyy/MM/dd E HH:mm"))


        }
    }

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when(event){

            Lifecycle.Event.ON_CREATE -> {
                val timeReceiverFilter = IntentFilter()
                timeReceiverFilter.addAction(Intent.ACTION_TIME_TICK)
                context.registerReceiver(this, timeReceiverFilter)

            }
            Lifecycle.Event.ON_RESUME -> {
                TimeCallback.timeInterface = context as TimeCallback.TimeInterface
            }
            Lifecycle.Event.ON_DESTROY -> {
                TimeCallback.timeInterface = null
                context.unregisterReceiver(this)
            }
            else -> {}
        }
    }
}